import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/fun/News.dart';
import 'package:mfkb/pages/fun/NewsList.dart';
import 'package:mfkb/pages/fun/SchoolFunList.dart';
import 'package:mfkb/pages/modules/CustomRoute.dart';
import 'package:mfkb/pages/web/WebViewByUrl.dart';
import 'package:mfkb/pages/web/WebViewPlugin.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/FunService.dart';
import 'package:mfkb/util/ColorUtil.dart';
import 'package:path_provider/path_provider.dart'; 
import 'package:toast/toast.dart'; 

import 'package:crypto/crypto.dart';
import 'package:convert/convert.dart';

class FunWidget extends StatefulWidget {
  @override
  _FunWidgetState createState() => _FunWidgetState();
}

class _FunWidgetState extends State<FunWidget> {
  dynamic list = [
    {"img":"" , "type":0 , "url":""}
  ] ;

  dynamic funList = {
    "page":1 ,
    "list":[
      [
        {"icon":"assets/images/cj.png" , "type":"local" , "url":"score" , "title":"成绩查询"} ,
        {"icon":"assets/images/ks.png" , "type":"local" , "url":"exam" , "title":"考试查询"} ,
        {"icon":"assets/images/df.png" , "type":"local" , "url":"electricty" , "title":"电费查询"} ,
        // {"icon":"assets/images/kjs.png" , "type":"local" , "url":"" , "title":"查空教室"} ,
        // {"icon":"assets/images/qxkb.png" , "type":"local" , "url":"" , "title":"全校课表"} ,
        {"icon":"assets/images/lxfs.png" , "type":"local" , "url":"relation" , "title":"联系方式"} ,
      ] ,
    ]
  } ;

  dynamic newsList = [
    {"cover":"" , "title":"校车发车时间" , "url":"" , "color":"#F6F5F8" , "font":"" , "bar":0 , "md":""} ,
    {"cover":"" , "title":"校车发车时间" , "url":"" , "color":"#F6F5F8" , "font":"" , "bar":0 , "md":""} ,
    {"cover":"" , "title":"校车发车时间" , "url":"" , "color":"#F6F5F8" , "font":"" , "bar":0 , "md":""} ,
    {"cover":"" , "title":"校车发车时间" , "url":"" , "color":"#F6F5F8" , "font":"" , "bar":0 , "md":""} ,
  ] ;

  dynamic schoolFun = [ 
    {"icon":"assets/images/kd.png" , "title":"宽带办理" , "type":"local" , "url":"broad"} ,
    {"icon":"assets/images/sjcz.png" , "title":"话费充值" , "type":"local" , "url":"phone"} ,
    {"icon":"assets/images/jx.png" , "title":"驾校报名" , "type":"local" , "url":"driver"} ,
  ] ;

  @override
  void initState() {
    super.initState();
    if(Config().getSpf().getString("funMd5") == null || Config().getSpf().getString("funMd5") == ""){
      download() ;
    }else{
      if(!Config().fun){
        FunService().checkFun().then((value){
          print(value) ;
          if(value["code"] == 200){
            Config().fun = true ;
            if(Config().getSpf().getString("funMd5") == value["data"]){
              loadResource() ;
            }else{
              download() ;
            }
          }else{
            loadResource() ;
          }
        }) ;
      }else{
        loadResource() ;
      }
    }
  }

  loadResource(){
    print("laile") ;
    String data = Config().getFunData() ;
    print(data) ;
    dynamic value = jsonDecode(data) ;
    newsList = jsonDecode(value["news"]) ;
    list = jsonDecode(value["banners"]) ;
    funList = jsonDecode(value["funList"]) ;
    List temp = jsonDecode(value["schoolFun"]) ;
    schoolFun = temp.length < 3 ? temp.sublist(0 , temp.length) : temp.sublist(0 , 3) ;
    setState(() {});
  }

  download(){
    FunService().init().then((value){
      if(value["code"] == 200){
        Config().setFunData(jsonEncode(value["data"])) ;
        newsList = jsonDecode(value["data"]["news"]) ;
        list = jsonDecode(value["data"]["banners"]) ;
        funList = jsonDecode(value["data"]["funList"]) ;
        List temp = jsonDecode(value["data"]["schoolFun"]) ;
        schoolFun = temp.length < 3 ? temp.sublist(0 , temp.length) : temp.sublist(0 , 3) ;
        List arr = [value["data"]["banners"] , value["data"]["news"] , value["data"]["funList"] , value["data"]["schoolFun"]] ;
        arr.sort() ;
        String d = arr.join("") ;
        var content = new Utf8Encoder().convert(d);
        var digest = md5.convert(content);
        Config().getSpf().setString("funMd5", hex.encode(digest.bytes)) ;
        setState(() {});
      }else{
        Toast.show(value["msg"], context) ;
      }
    }) ;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        width: ScreenUtil().setWidth(375) ,
        height:ScreenUtil().setHeight(812) ,
        decoration: BoxDecoration(
          color: Colors.white
        ),
        child: Column(
          children: <Widget>[
            Container(
              height:MediaQuery.of(context).padding.top ,
            ) ,
            Expanded(
              child: Container(
                child: ScrollConfiguration(
                  behavior: MyBehavior() ,
                  child: ListView(
                    padding: EdgeInsets.only(top:0),
                    children: <Widget>[
                      Container(
                        width:ScreenUtil().setWidth(375) ,
                        height:33 ,
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:6),
                        child: Text("功能" , style: TextStyle(
                          color: Color.fromARGB(255, 71, 80, 98),
                          fontSize: 26 ,
                          height:1.3 ,
                          fontWeight: FontWeight.bold ,
                          fontFamily: "Alibaba-PuHuiTi-B,Alibaba-PuHuiTi"
                        ),),
                      ) ,
                      Container(
                        width:ScreenUtil().setWidth(345) ,
                        height:ScreenUtil().setHeight(110) ,
                        // 设置圆角无效
                        // decoration: BoxDecoration(
                        //   borderRadius: BorderRadius.all(Radius.circular(20))
                        // ),
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(16) , right:ScreenUtil().setWidth(15)),
                        child: Swiper(
                          itemCount: list.length ,
                          autoplay: true,
                          scale: 0.9,
                          //loop:false ,
                          itemBuilder: (BuildContext context,int index){
                            // 使用缓存图片类
                            return ClipRRect(
                              borderRadius: BorderRadius.all(Radius.circular(15)),
                              child: GestureDetector(
                                child: CachedNetworkImage(
                                  imageUrl: Config().getImgHost()+list[index]["img"] ,
                                  fit: BoxFit.fill ,
                                  placeholder: (context , url){
                                    return (
                                      Container(
                                        color: Color.fromARGB(255, 246, 245, 248),
                                        child: Center(
                                          child: Image.asset("assets/images/imageloading.png"),
                                        ),
                                      )
                                    ) ;
                                  },
                                ),
                                onTap: (){
                                  if(list[index]["type"] == 1){
                                    Navigator.of(context).push(CustomRoute(WebViewByUrl(url: list[index]["url"]))) ;
                                  }
                                } ,
                              )
                            ) ;
                          },
                        )
                      ) ,
                      Container(
                        height: ScreenUtil().setHeight(155),
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(33) , right:ScreenUtil().setWidth(33) , top:ScreenUtil().setHeight(30)),
                        child: Swiper(
                          loop: false,
                          autoplay: false,
                          itemCount: funList["page"] ,
                          itemBuilder: (context , index){
                            return Wrap(
                              runSpacing: ScreenUtil().setHeight(30),
                              children: getWidgetList(funList["list"][index]),
                              spacing: ScreenUtil().setWidth(31),
                            ) ;
                          },
                        ),
                      ) ,
                      Container(
                        height: ScreenUtil().setHeight(30),
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(36)) ,
                        child: Row(
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setWidth(190),
                              height: ScreenUtil().setHeight(27) ,
                              margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
                              child: Text(
                                "校园资讯" , style: TextStyle(
                                  fontFamily: "Alibaba-PuHuiTi-M,Alibaba-PuHuiTi" ,
                                  fontSize: ScreenUtil().setSp(18) ,
                                  fontWeight: FontWeight.bold ,
                                  color: Color.fromARGB(255, 19, 28, 53) ,
                                  height: ScreenUtil().setHeight(27) / ScreenUtil().setSp(18)
                                ),
                              ),
                            ) ,
                            Expanded(
                              child: Container(
                                height: ScreenUtil().setHeight(20),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: GestureDetector(
                                        child: Container(
                                          color: Color.fromARGB(0, 0, 0, 0),
                                          child: Text("查看更多" , style: TextStyle(
                                            fontSize: ScreenUtil().setSp(13) ,
                                            color: Color.fromARGB(255, 121, 132, 155) ,
                                            fontWeight: FontWeight.w500 , 
                                            height: ScreenUtil().setHeight(20) / ScreenUtil().setSp(13)
                                          ),textAlign: TextAlign.right,),
                                        ),
                                        onTap: (){
                                          Navigator.of(context).push(CustomRoute(NewsList())) ;
                                        },
                                      ),
                                    ) ,
                                    Container(
                                      width: ScreenUtil().setHeight(18),
                                      height: ScreenUtil().setHeight(18),
                                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)),
                                      child: Image.asset("assets/images/more_2x.png"),
                                    )
                                  ],
                                ),
                              ),
                            ) 
                          ],
                        ),
                      ) ,
                      Container(
                        height:ScreenUtil().setHeight(125) ,
                        //color: Colors.red ,
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(12)),
                        child: ListView(
                          scrollDirection: Axis.horizontal ,
                          children: newsWidget()
                        ),
                      ) ,
                      Container(
                        height: ScreenUtil().setHeight(30),
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(29)) ,
                        child: Row(
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setWidth(190),
                              height: ScreenUtil().setHeight(27) ,
                              margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
                              child: Text(
                                "本校服务" , style: TextStyle(
                                  fontFamily: "Alibaba-PuHuiTi-M,Alibaba-PuHuiTi" ,
                                  fontSize: ScreenUtil().setSp(18) ,
                                  fontWeight: FontWeight.bold ,
                                  color: Color.fromARGB(255, 19, 28, 53) ,
                                  height: ScreenUtil().setHeight(27) / ScreenUtil().setSp(18)
                                ),
                              ),
                            ) ,
                            Expanded(
                              child: Container(
                                height: ScreenUtil().setHeight(20),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: GestureDetector(
                                        child: Container(
                                          child: Text("查看更多" , style: TextStyle(
                                            fontSize: ScreenUtil().setSp(13) , 
                                            color: Color.fromARGB(255, 121, 132, 155) ,
                                            fontWeight: FontWeight.w500 , 
                                            height: ScreenUtil().setHeight(20) / ScreenUtil().setSp(13)
                                          ),textAlign: TextAlign.right,),
                                        ),
                                        onTap: (){
                                          print(Config().getFunData()) ;
                                          List data = jsonDecode(jsonDecode(Config().getFunData())["schoolFun"]) ;
                                          Navigator.of(context).push(CustomRoute(SchoolFunList(data: data,))) ;
                                        },
                                      ),
                                    ) ,
                                    Container(
                                      width: ScreenUtil().setHeight(18),
                                      height: ScreenUtil().setHeight(18),
                                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)),
                                      child: Image.asset("assets/images/more_2x.png"),
                                    )
                                  ],
                                ),
                              ),
                            ) 
                          ],
                        ),
                      ) ,
                      Container(
                        height:ScreenUtil().setHeight(46) ,
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(12) , right:ScreenUtil().setWidth(14)),
                        child: Row(
                          children: schoolFunWidget()
                        ),
                      ) ,
                    ],
                  ),
                )
              )
            )
          ]
        )
      ),
    );
  }

  schoolFunWidget(){
    return List.generate(schoolFun.length, (index){
      return GestureDetector(
        child: Container(
          width: ScreenUtil().setWidth(110),
          height: ScreenUtil().setHeight(46),
          margin: EdgeInsets.only(left:index == 0 ? 0 : ScreenUtil().setWidth(8)),
          decoration: BoxDecoration(
            color: Colors.white ,
            border: Border.all(
              color: Color.fromARGB(255, 216, 220, 227) ,
              style: BorderStyle.solid
            ) ,
            borderRadius: BorderRadius.all(Radius.circular(12))
          ),
          child: Row(
            children: <Widget>[
              Container(
                width: ScreenUtil().setWidth(30),
                height: ScreenUtil().setHeight(30),
                margin: EdgeInsets.only(left:ScreenUtil().setWidth(7)),
                child:schoolFun[index]["type"] == "local" ? Image.asset(schoolFun[index]["icon"]) : CachedNetworkImage(imageUrl: schoolFun[index]["icon"]) ,
              ) ,
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
                  child: Text(schoolFun[index]["title"] , style: TextStyle( 
                    fontSize: 12 ,
                    color: Color.fromARGB(255, 121, 132, 155) ,
                    fontWeight: FontWeight.bold ,
                    fontFamily: "PingFang-SC-Bold,PingFang-SC" 
                  ),),
                ),
              )
            ],
          ),
        ) ,
        onTap: (){
          if(schoolFun[index]["type"] == "local"){ 
            if(schoolFun[index]["url"] != null && schoolFun[index]["url"] != ""){ 
              Navigator.of(context).pushNamed(schoolFun[index]["url"]) ;
            }
          }else{
            Navigator.of(context).push(CustomRoute(WebViewPlugin(file:schoolFun[index]["file"] , md5: schoolFun[index]["md5"],type: 2,))) ;
          }
        },
      ) ;
    }) ;
  }

  getWidgetList(dynamic data){
    return List.generate(data.length, (index){
      return Container(
        width: ScreenUtil().setWidth(54),
        height: ScreenUtil().setHeight(62),
        // margin: EdgeInsets.only(left:index == 0 || index == 4 ? 0 : ScreenUtil().setWidth(31)) ,
        //color: Colors.red,
        child: GestureDetector(
          child: Container(
            color: Color.fromARGB(0, 0, 0, 0),
            child: Column(
              children: <Widget>[
                Container(
                  height:ScreenUtil().setHeight(36) ,
                  width: ScreenUtil().setWidth(36) ,
                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(6) , right:ScreenUtil().setWidth(6)),
                  child: data[index]["type"] == "local" ? Image.asset(data[index]["icon"]) : CachedNetworkImage(imageUrl: Config().getImgHost()+data[index]["icon"]),
                ) ,
                Expanded(
                  child: Center( 
                    child: Text(data[index]["title"] , style: TextStyle(
                      fontSize: 12 ,
                      fontFamily: "PingFang-SC-Medium,PingFang-SC" ,
                      fontWeight: FontWeight.w500 ,
                      color: Color.fromARGB(255, 121, 132, 155)
                    ),),
                  )
                )
              ],
            ),
          ),
          onTap: (){
            if(data[index]["type"] == "local"){ 
              if(data[index]["url"] != null && data[index]["url"] != ""){ 
                Navigator.of(context).pushNamed(data[index]["url"]) ;
              }
            }else{
              Navigator.of(context).push(CustomRoute(WebViewPlugin(file:data[index]["file"] , md5: data[index]["md5"],type: 2,))) ;
            }
          },
        )
      ) ;
    }) ;
  }

  newsWidget(){
    return List.generate(newsList.length, (index){
      return Container(
        width: ScreenUtil().setWidth(120),
        margin: EdgeInsets.only(left:index == 0 ? 0 : ScreenUtil().setWidth(10)),
        //color: Colors.red,
        child: GestureDetector(
          child: Column(
            children: <Widget>[
              Container(
                height:ScreenUtil().setHeight(87.5) ,
                width: ScreenUtil().setWidth(120),
                child: ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  child: CachedNetworkImage(
                    imageUrl: Config().getImgHost()+newsList[index]["cover"] ,
                    fit: BoxFit.fill ,
                    placeholder: (context , url){
                      return (
                        Container(
                          color: Color.fromARGB(255, 246, 245, 248),
                          child: Center(
                            child: Image.asset("assets/images/imageloading.png"),
                          ),
                        )
                      ) ;
                    } ,
                  ),
                )
              ) ,
              Expanded( 
                child: Center(
                  child: Container(
                    width: ScreenUtil().setWidth(120),
                      child: Text(newsList[index]["title"] , style: TextStyle( 
                        fontSize: 13 ,
                        fontFamily: "PingFang-SC-Medium,PingFang-SC" ,
                        fontWeight: FontWeight.bold ,
                        color: Color.fromARGB(255, 78, 86, 108) ,
                      ),overflow: TextOverflow.ellipsis,), 
                  ) 
                )
              )
            ],
          ),
          onTap: (){ 
            print(newsList[index]["type"]) ;
            if(newsList[index]["type"] == 1){
              Navigator.of(context).push(CustomRoute(WebViewPlugin(file: newsList[index]["file"], md5: newsList[index]["file_md5"] , type: 1,))) ;
            }else if(newsList[index]["type"] == 2){
              Navigator.of(context).push(CustomRoute(WebViewByUrl(url: newsList[index]["file"]))) ;
            }
          },
        )
      ) ;
    }) ;
  }
}